﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DAPNet
{
    public class QuadraticMeanFilter : IOfflineEffect
    {
        private int parameter;


        public QuadraticMeanFilter(int parameter)
        {
            this.parameter = parameter;
        }

        public int Parameter
        {
            get 
            { 
                return parameter; 
            }
            set 
            { 
                parameter = value; 
            }
        }

        public void Process(SampleCollection samples)
        {
            SampleCollection clonedSamples = samples.Clone();
            for (int i = 0; i < samples.Count; i++)
            {
                double quadraticMeanValue = GetQuadraticMeanValueAt(clonedSamples, i);
                samples[i].SetTrimmedValue(quadraticMeanValue);
            }
        }

        private double GetQuadraticMeanValueAt(SampleCollection samples, int index)
        {
            int startIndex = index - parameter;
            int endIndex = index + parameter;
            double sumOfSquaredValues = 0;
            for (int i = startIndex; i <= endIndex; i++)
            {
                if (i >= 0 && i < samples.Count)
                {
                    sumOfSquaredValues += samples[i].Value * samples[i].Value;
                }
            }
            double windowSize = (parameter * 2 + 1);
            double quadraticMeanValue = Math.Sqrt(sumOfSquaredValues / windowSize);
            return quadraticMeanValue;
        } 
    }
}
